package io.sage.modules.rxtx.service.impl;

import com.alibaba.fastjson.JSONObject;
import io.sage.common.config.IndustrySMS;
import io.sage.common.utils.BatchNumber;

import io.sage.modules.basics.entity.BWarehouse;
import io.sage.modules.basics.service.BWarehouseService;
import io.sage.modules.goods.entity.BGoods;
import io.sage.modules.goods.entity.BGoodsExample;
import io.sage.modules.goods.enums.GoodsStatusEnum;
import io.sage.modules.goods.service.BGoodsService;
import io.sage.modules.hcnet.service.HcNetRadioService;
import io.sage.modules.outwarehouse.entity.BEmployeeAccessRecord;
import io.sage.modules.outwarehouse.service.BEmployeeAccessRecordService;
import io.sage.modules.outwarehouse.service.BGoodsReceiveRecordService;
import io.sage.modules.rxtx.service.RxtxService;
import io.sage.modules.socket.service.SocketClientService;
import io.sage.modules.sys.dao.SysUserMapper;
import io.sage.modules.sys.entity.SysUserEntity;
import io.sage.modules.warn.entity.BRfidWarmConf;
import io.sage.modules.warn.entity.BRfidWarn;
import io.sage.modules.warn.enums.BRfidWarmConfTypeEnum;
import io.sage.modules.warn.service.BRfidWarmConfService;
import io.sage.modules.warn.service.BRfidWarnService;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by Mafy on 2019/7/12.
 * 扫描标签处理service
 */
@Service
public class RxtxServiceImpl implements RxtxService {

    private static Logger logger = LoggerFactory.getLogger(RxtxServiceImpl.class);

    @Resource
    private BGoodsService bGoodsService;
    @Resource
    private BWarehouseService bWarehouseService;

    @Resource
    private BGoodsReceiveRecordService bGoodsReceiveRecordService;
    @Resource
    private BEmployeeAccessRecordService bEmployeeAccessRecordService;

    @Resource
    private BRfidWarnService bRfidWarnService;

    @Resource
    private HcNetRadioService hcNetRadioService;

    @Resource
    private SysUserMapper sysUserMapper;


    @Resource
    private SocketClientService socketClientService;

    @Resource
    private BRfidWarmConfService bRfidWarmConfService;
    //开启485协议开关地址为1
    String msg="01050000FF008C3A";
    List<String> list = new ArrayList<>();
    Timer timer = new Timer(); //timer单例对象
    long oldTime = 0; //上次存入list数据的时间
    long delayTime = 10000;//10s

    //目前只需要监测出的id
    @Override
    public synchronized void lableDataHandle(String lableId){
        try {
            long nowTime = System.currentTimeMillis();
            if(nowTime-oldTime>delayTime){
                list.clear();
            }else{
                timer.cancel();
            }
            timer = new Timer();
            oldTime = nowTime;
            logger.info("最新领取时间：{}",oldTime);
            //判断如果不包含，则放到list中
            if(!list.contains(lableId)){
                list.add(lableId);
            }
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //处理list
                    checkAllLable();
                }
            },delayTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public int findGoodsByEpc(String epc){
        Map<String,Object>map=new HashMap<>();
        map.put("labelErp", epc);
        List list=bGoodsService.selectGoodsList(map);
        return list.size();
    }
    //处理list中所有的lable
    @Transactional
    private void checkAllLable(){
        logger.info("执行时间：{}",System.currentTimeMillis());
        logger.info("此时list数据有：{}", JSONObject.toJSON(list));
        BGoodsExample bGoodsExample = new BGoodsExample();
        BGoodsExample.Criteria criteria = bGoodsExample.createCriteria();
        //此处需要改为lableID字段
        criteria.andLabelErpIn(list);

        List<BGoods> bGoods = bGoodsService.selectByExample(bGoodsExample);
        List<Integer> ecceptionBGoodsList = new ArrayList();//正常
        List<Integer> appointmentBGoodsList = new ArrayList();//预约
        StringBuffer bReturnRecords = new StringBuffer();//归还id字符串拼接
        StringBuffer appointmentGoodsIds = new StringBuffer();//领取id字符串拼接
        List<Integer> normalBGoodsList = new ArrayList();//包括借出和预约的

        List<BRfidWarn> bRfidWarns = new ArrayList<>();
        BEmployeeAccessRecord bEmployeeAccessRecord=new BEmployeeAccessRecord();



        String batch = BatchNumber.createSerial("SQPC", 2);//批次
        for (int i = 0; i < bGoods.size(); i++) {
            BGoods everyGood = bGoods.get(i);
            if (ObjectUtils.nullSafeEquals(everyGood.getGoodsStatus(), GoodsStatusEnum.NORMAL.getCode())||ObjectUtils.nullSafeEquals(everyGood.getGoodsStatus(), GoodsStatusEnum.WAITCHECK.getCode())){//正常
                // 正常状态，在该处的话，则为未申请处理，属于异常情况
                ecceptionBGoodsList.add(everyGood.getId());
                BRfidWarn b= new BRfidWarn();
                b.setGoodsId(everyGood.getId());
                b.setBatch(batch);
                b.setCreateTime(new Date());
                b.setUpdateTime(new Date());
                b.setIsUsed(1);
                b.setIsDel(0);
                bRfidWarns.add(b);
            }else if(ObjectUtils.nullSafeEquals(everyGood.getGoodsStatus(), GoodsStatusEnum.APPLY.getCode())){//预约
                appointmentGoodsIds.append(everyGood.getId()).append(",");
                appointmentBGoodsList.add(everyGood.getId());
                normalBGoodsList.add(everyGood.getId());
            }else if(ObjectUtils.nullSafeEquals(everyGood.getGoodsStatus(), GoodsStatusEnum.LEND.getCode())){//借出
                bReturnRecords.append(everyGood.getId()).append(",");
                normalBGoodsList.add(everyGood.getId());
            }

        }
        //for --end

        //领取状态修改在该处处理，物品申请表中状态修改
        if(normalBGoodsList.size()>0){

            logger.info("物品领取状态修改，{}",normalBGoodsList);
            int i = bGoodsService.updateStatusByIds(normalBGoodsList);//修改正常数据的状态


            //申请表状态修改
            if(appointmentGoodsIds.length()>0){
                String appointmentGoodsIdStr = appointmentGoodsIds.toString().substring(0,appointmentGoodsIds.length()-1);
                Map<String,Object> param = new HashMap<>();
                param.put("goodsIds",appointmentGoodsIdStr);
                param.put("status",1);//1领取
                param.put("returnTime",null);
                param.put("updateTime",new Date());
                int a = bGoodsReceiveRecordService.updateStatus(param);
                int b=bEmployeeAccessRecordService.insertBatchBygoodsIds(param);
            }
        }

        //物品归还记录 -- 从物品领取表中获取
        if(bReturnRecords.length()>0){
            String leadBGoodsIdStr = bReturnRecords.toString().substring(0,bReturnRecords.length()-1);
            logger.info("物品归还记录，{}",leadBGoodsIdStr);
            Map<String,Object> param = new HashMap<>();
            param.put("goodsIds",leadBGoodsIdStr);
            param.put("status",2);//2归还
            param.put("returnTime",new Date());
            param.put("updateTime",null);
            //归还--申请表状态修改
            int a = bGoodsReceiveRecordService.updateStatus(param);
            int b=bEmployeeAccessRecordService.insertBatchBygoodsIds(param);
        }

        //报警表保存数据
        if(ecceptionBGoodsList.size()>0){
            List<BRfidWarmConf> bRfidWarmConfs=this.bRfidWarmConfService.findByGoodId(bRfidWarns.get(0).getGoodsId());
            if(bRfidWarmConfs.size()>0){
                BRfidWarmConf bRfidWarmConf=bRfidWarmConfs.get(0);
                String[] list=bRfidWarmConf.getType().split(",");
                int i = bRfidWarnService.batchInsert(bRfidWarns);//报警表保存,bRfidWarns里面在insert之后，会有id返回，直接使用bRfidWarns传到录像那儿，然后保存录像数据到数据库
                for (String str:list) {
                    if(!StringUtils.isEmpty(str)){
                    	//报警鸣笛
                        if(BRfidWarmConfTypeEnum.ALARM.getCode() == Integer.parseInt(str)){
                            socketClientService.sendMsg(msg);
                        }
                        //录像
                        if(BRfidWarmConfTypeEnum.VIDEO.getCode() == Integer.parseInt(str)){
                        	//todo 
                            boolean b = hcNetRadioService.hcNetSaveRadio1(bRfidWarns);//录像
                        }
                        HashSet<String> set=new HashSet<>();

                        if(BRfidWarmConfTypeEnum.MSG.getCode() == Integer.parseInt(str)||BRfidWarmConfTypeEnum.PHONE.getCode() == Integer.parseInt(str)){

                             List<BWarehouse>warehouses=bWarehouseService.selectByGoodsIds(ecceptionBGoodsList);
                            for (int j = 0; j < warehouses.size(); j++) {
                                List<SysUserEntity> userEntityList=this.sysUserMapper.queryByWarehouseId(warehouses.get(j).getId());
                                warehouses.get(j).setUsers(userEntityList);
                            }
                            if(BRfidWarmConfTypeEnum.MSG.getCode() == Integer.parseInt(str)){
                                for (int j = 0; j < warehouses.size(); j++) {
                                    for (int k = 0; k < warehouses.get(i).getUsers().size(); k++) {
                                        IndustrySMS.execute(warehouses.get(i).getUsers().get(k).getMobile(), warehouses.get(i).getAntennaName(), "172462");
                                    }
                                }
                            }else{
                                for (int j = 0; j < warehouses.size(); j++) {
                                    for (int k = 0; k < warehouses.get(i).getUsers().size(); k++) {
                                        IndustrySMS.executeMusic(warehouses.get(i).getUsers().get(k).getMobile(), warehouses.get(i).getAntennaName(), "1562");
                                    }
                                }
                            }
                        }

                    }

                }
            }else{

                boolean b = hcNetRadioService.hcNetSaveRadio1(bRfidWarns);//录像
                //485开关,报警
                socketClientService.sendMsg(msg);
            }

        }
    }
}
